from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
# Create your views here.
from myapp.models import *


# 校验用户是否存在
class CheckUserName(APIView):
    def get(self, request, name):
        # 获取数据库的用户名看有几个
        rest = User.objects.filter(username=name).count()
        # 大于0说明已经存在
        if rest > 0:
            return Response(
                {'msg': '用户名已经存在', 'code': 400}
            )
        return Response({'code': 200})


# 校验手机号是否存在
class CheckMobile(APIView):
    # 获取数据库的手机号看有几个
    def get(self, request, mobile):
        rest = User.objects.filter(mobile=mobile).count()
        # 大于0说明已经存在
        if rest > 0:
            return Response(
                {'msg': '手机号已经存在', 'code': 400}
            )
        return Response({'code': 200})


# 注册
class CheckRegister(APIView):
    def post(self, request):
        # 获取前端输入的数据进行校验
        name = request.data.get('userName')
        pwd = request.data.get('pwd')
        mobile = request.data.get('mobile')
        agree = request.data.get('agree')
        # 判断字段不能为空
        if not all([name, pwd, mobile, agree]):
            return Response({'msg': '填写完整的信息', 'code': 400})
        # 判断协议是否勾选
        if not agree:
            return Response({'msg': '请勾选协议', 'code': 400})
        # 存入数据库
        User.objects.create_user(username=name, password=pwd, mobile=mobile, agree=agree)
        return Response({'msg': '注册成功', 'code': 200})
